package com.project.myxima;

import android.content.Intent;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.lcodecore.tkrefreshlayout.header.bezierlayout.BezierLayout;
import com.project.myxima.adapters.DetailAdapter;
import com.project.myxima.base.BaseActivity;
import com.project.myxima.interfaces.IAlbumDetailViewCallback;
import com.project.myxima.interfaces.IPlayerCallback;
import com.project.myxima.interfaces.ISubCallback;
import com.project.myxima.presenters.AlbumDetailPresenter;
import com.project.myxima.presenters.PlayerPresenter;
import com.project.myxima.presenters.SubscribePresenter;
import com.project.myxima.utils.ImageBlur;
import com.project.myxima.utils.LogUtils;
import com.project.myxima.views.RoundRectImageView;
import com.project.myxima.views.UILoader;
import com.squareup.picasso.Callback;
import com.squareup.picasso.Picasso;
import com.ximalaya.ting.android.opensdk.model.album.Album;
import com.ximalaya.ting.android.opensdk.model.track.Track;
import com.ximalaya.ting.android.opensdk.player.service.XmPlayListControl;

import net.lucode.hackware.magicindicator.buildins.UIUtil;

import java.util.List;

public class DetailActivity extends BaseActivity implements IAlbumDetailViewCallback, UILoader.OnRetryClickListener, DetailAdapter.ItemClickListener, IPlayerCallback , ISubCallback {

    private static final String TAG = "DetailActivity";
    private ImageView mLargeCover;
    private RoundRectImageView mSmallCover;
    private TextView mAlbumTitle;
    private TextView mAlbumAuthor;
    private AlbumDetailPresenter mAlbumDetailPresenter;
    private int mCurrentPage = 1;
    private RecyclerView mDetailList;
    private DetailAdapter mDetailAdapter;
    private FrameLayout mDetailListContainer;
    private UILoader mUILoader;
    private long mCurrentId = -1;
    private ImageView mPlayControlBtn;
    private TextView mPlayControlTv;
    private PlayerPresenter mPlayerPresenter;
    private List<Track> mCurrentPlayList = null;
    private static final int DEFAULT_PLAY_POSITION = 0;
    private TwinklingRefreshLayout mRefreshLayout;

    private boolean mIsLoadMore = false;
    private Track mCurrentTrack;
    private TextView mSubscribe_tv;
    private boolean mIsSubscribed;
    private SubscribePresenter mSubscribePresenter;
    private Album mAlbum;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detail);

        //设置是否隐藏状态栏和导航栏
        /*int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN;
            //上面参数：隐藏状态栏
        getWindow().getDecorView().setSystemUiVisibility(uiOptions);*/


        initView();
        initPresenter();

        mSubscribePresenter.isSubscribed(mAlbum);
        //mSubscribePresenter.isSubscribed(mAlbum);
        updatePlayState(mPlayerPresenter.isPlaying());

        initEvent();
    }

    private void initPresenter() {
        mAlbumDetailPresenter = AlbumDetailPresenter.getInstance();
        mAlbumDetailPresenter.registerViewCallback(this);

        mPlayerPresenter = PlayerPresenter.getPlayerPresenter();
        mPlayerPresenter.registerViewCallback(this);

        mSubscribePresenter = SubscribePresenter.getSubscribePresenter();
        mSubscribePresenter.registerViewCallback(this);

    }


    private void initEvent() {
        mPlayControlBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mPlayerPresenter != null){
                    boolean hasPlayList = mPlayerPresenter.isPlayListSet;
                    if(hasPlayList){
                        handlePlayControl();
                    }else{
                        handleNoPlayList();
                    }
                }
            }
        });

        BezierLayout headView = new BezierLayout(this);
        mRefreshLayout.setHeaderView(headView);
        mRefreshLayout.setMaxHeadHeight(140);
        mRefreshLayout.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onRefresh(TwinklingRefreshLayout refreshLayout) {
                super.onRefresh(mRefreshLayout);
                if (mAlbumDetailPresenter != null) {
                    mAlbumDetailPresenter.loadMore();
                }


            }

            @Override
            public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
                super.onLoadMore(mRefreshLayout);
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        //Toast.makeText(DetailActivity.this,"pullUp to Load more",Toast.LENGTH_SHORT).show();
                        mAlbumDetailPresenter.loadMore();
                        mIsLoadMore = true;
                    }
                }, 2000);
            }
        });



        //subscribed
        mSubscribe_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mIsSubscribed){
                    mSubscribePresenter.deleteSubscribe(mAlbum);
                    updateSubStatus(false);
                }else {
                    mSubscribePresenter.addSubscribe(mAlbum);
                    updateSubStatus(true);
                }
            }
        });
    }

    /**
     * update subscribe status of current Album and change UI
     * @param isSubscribed
     */
    private void updateSubStatus(boolean isSubscribed) {
        mIsSubscribed = isSubscribed;
        if(mIsSubscribed){
            mSubscribe_tv.setText(R.string.detail_subscribe_text);
        }else {
            mSubscribe_tv.setText(R.string.detail_unsubscribe_text);
        }
    }

    private void handleNoPlayList() {
        mPlayerPresenter.setPlayList(mCurrentPlayList, DEFAULT_PLAY_POSITION);
    }

    private void handlePlayControl() {
        if(mPlayerPresenter.isPlaying()){
            mPlayerPresenter.pause();
        }else{
            mPlayerPresenter.play();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mAlbumDetailPresenter.unregisterViewCallback(this);
    }

    private void initView() {

        mDetailListContainer = this.findViewById(R.id.detail_list_container);
        //当为空时，创建UILoader
        if (mUILoader == null) {
            mUILoader = new UILoader(this) {
                @Override
                protected View getSuccessView(ViewGroup container) {
                    return createSuccessView(container);
                }
            };
        }

        mDetailListContainer.removeAllViews();
        mDetailListContainer.addView(mUILoader);
        //设置网络错误监听器
        mUILoader.setOnRetryClickListener(DetailActivity.this);

        mLargeCover = this.findViewById(R.id.iv_large_cover);
        mSmallCover = this.findViewById(R.id.riv_small_cover);
        mAlbumTitle = this.findViewById(R.id.tv_album_title);
        mAlbumAuthor = this.findViewById(R.id.tv_album_author);

        mPlayControlBtn = this.findViewById(R.id.detail_play_control_iv);
        mPlayControlTv = this.findViewById(R.id.detail_play_control_text);
        mPlayControlTv.setSelected(true);

        //Refresh part
        mRefreshLayout = this.findViewById(R.id.refresh_layout);

        //Subscribe
        mSubscribe_tv = this.findViewById(R.id.detail_subscribe_tv);

    }

    private View createSuccessView(ViewGroup container) {
        //setContentView(R.layout.item_detail_list);
        View detailListView = LayoutInflater.from(this).inflate(R.layout.item_detail_list, container, false);//没有创造自定义控件前都填false
        mDetailList = detailListView.findViewById(R.id.album_detail_list);

        //使用recycleview
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        mDetailList.setLayoutManager(layoutManager);
        mDetailAdapter = new DetailAdapter();
        mDetailList.setAdapter(mDetailAdapter);

        mDetailList.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                outRect.top = UIUtil.dip2px(view.getContext(),2);
                outRect.bottom = UIUtil.dip2px(view.getContext(),2);
                outRect.left = UIUtil.dip2px(view.getContext(),2);
                outRect.right = UIUtil.dip2px(view.getContext(),2);
            }
        });

        mDetailAdapter.setItemClickListener(this);

        return detailListView;
    }




    @Override
    public void onDetailListLoaded(List<Track> tracks) {

        if(mIsLoadMore && mRefreshLayout != null){
            mIsLoadMore = false;
            mRefreshLayout.finishLoadmore();
        }

        mRefreshLayout.finishRefreshing();

        this.mCurrentPlayList = tracks;
        //根据结果，控制UI显示
        if (tracks == null || tracks.size() == 0) {
            if (mUILoader != null) {
                mUILoader.updateStatus(UILoader.UIStatus.EMPTY);
            }
        }

        if (mUILoader != null) {
            mUILoader.updateStatus(UILoader.UIStatus.SUCCESS);
        }

        mDetailAdapter.setData(tracks);
    }

    /**
     * 网络发生错误，处理UI
     * @param errorCode
     * @param errorMsg
     */
    @Override
    public void onNetworkError(int errorCode, String errorMsg) {
        mUILoader.updateStatus(UILoader.UIStatus.NETWORK_ERROR);
    }

    @Override
    public void onAlbumLoaded(Album album) {

        long id = album.getId();
        mCurrentId = id;
        mAlbum = album;


        LogUtils.d(TAG,"album id ---->"  + id);
        if (mAlbumDetailPresenter != null) {
            mAlbumDetailPresenter.getAlbumDetail((int) id,mCurrentPage);
        }

        //拿数据，显示Loading状态
        if (mUILoader != null) {
            mUILoader.updateStatus(UILoader.UIStatus.LOADING);
        }

         //设置数据
        if(mAlbumTitle!=null){
            mAlbumTitle.setText(album.getAlbumTitle());
        }
        if (mAlbumAuthor != null) {
            mAlbumAuthor.setText(album.getAnnouncer().getNickname());
        }
        if (mLargeCover != null && null != mLargeCover) {
            Picasso.get().load(album.getCoverUrlLarge()).into(mLargeCover, new Callback() {
                @Override
                public void onSuccess() {
                    Drawable drawable = mLargeCover.getDrawable();
                    if (drawable != null) {
                        //到这里，说明图片不为空
                        ImageBlur.makeBlur(mLargeCover,DetailActivity.this);
                    }
                }
                @Override
                public void onError(Exception e) {
                    LogUtils.d(TAG,"封面图片加载失败");
                }
            });
        }

        if (mSmallCover != null ) Picasso.get().load(album.getCoverUrlLarge()).into(mSmallCover);

    }

    @Override
    public void onLoadMoreFinish(int trackSize) {
        if(trackSize > 0){
            Toast.makeText(this,"Successfully Load more " + trackSize + " tracks",Toast.LENGTH_SHORT).show();
        }else{
            Toast.makeText(this,"There is no more tracks",Toast.LENGTH_SHORT).show();

        }
    }

    @Override
    public void onRefreshFinish(int trackSize) {

    }

    @Override
    public void onRetryClick() {
        if (mAlbumDetailPresenter != null) {
            mAlbumDetailPresenter.getAlbumDetail((int) mCurrentId,mCurrentPage);
        }
    }

    @Override
    public void onItemClick(List<Track> list, int position) {
        //设置播放器的数据
        PlayerPresenter playerPresenter = PlayerPresenter.getPlayerPresenter();
        playerPresenter.setPlayList(list,position);
        //跳转到播放器页面
        Intent intent = new Intent(this,PlayerActivity.class);
        startActivity(intent);
    }

    private void updatePlayState(boolean isPlaying) {
        if (mPlayControlBtn != null && mPlayControlTv != null) {
            mPlayControlBtn.setImageResource(isPlaying ? R.drawable.selector_play_control_pause :
                                                        R.drawable.selector_play_control_play);
            if(!isPlaying){
                mPlayControlTv.setText(R.string.play_control_play_text);
            }else if(mCurrentTrack != null && isPlaying){
                mPlayControlTv.setText(mCurrentTrack.getTrackTitle());
            }
        }
    }


    //===============================  Callbacks for Player    =====================================
    @Override
    public void onPlayStart() {
        //change image to "pause",so do the text

        updatePlayState(true);

    }

    @Override
    public void onPlayPause() {
        updatePlayState(false);
    }

    @Override
    public void onPlayCompleted() {

    }

    @Override
    public void onPlayStop() {

    }

    @Override
    public void onPlayError() {

    }

    @Override
    public void onNextPlay(Track track) {

    }

    @Override
    public void onPrePlay(Track track) {

    }

    @Override
    public void onListLoaded(List<Track> list) {

    }

    @Override
    public void onPlayModeChange(XmPlayListControl.PlayMode playMode) {

    }

    @Override
    public void onProgressChange(int currentProgress, int total) {

    }

    @Override
    public void onAdLoading() {

    }

    @Override
    public void onAdFinished() {

    }

    @Override
    public void onTrackUpdate(Track track, int playIndex) {

        this.mCurrentTrack = track;

        // set text to mPlayControlTv
        if (track != null) {
            String trackTitle = track.getTrackTitle();
            if(!TextUtils.isEmpty(trackTitle) && mPlayControlTv != null){
                mPlayControlTv.setText(trackTitle);
            }
        }

    }

    //=================================================================

    //callback for Subsribe.

    @Override
    public void onAddSubscribe(boolean isSuccess) {
        updateSubStatus(true);
    }

    @Override
    public void onDeleteSubscribe(boolean isSuccess) {
        updateSubStatus(false);
    }

    @Override
    public void onSubscribeListLoaded(List<Album> albums) {

    }

    @Override
    public void isSubscribed(boolean isSub) {
        updateSubStatus(isSub);
    }

    @Override
    public void onSubscribeListLoadedError() {

    }
}
